﻿using Gma.QrCodeNet.Encoding;
using Gma.QrCodeNet.Encoding.Windows.Render;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;

namespace Infrastructure
{
    public class QrCreater
    {
        /// <summary>
        /// 生成二维码
        /// </summary>
        /// <param name="content">二维码内容</param>
        /// <param name="isUrl">是否带复数参网址</param>
        /// <param name="width">宽</param>
        /// <param name="height">高</param>
        /// <returns>二维码 Image 对象</returns>
        public System.Drawing.Image CreateImage(string content, bool isUrl = false, int width = 200, int height = 200)
        {
            if (string.IsNullOrWhiteSpace(content)) { return null; }
            QrEncoder encoder = new QrEncoder(ErrorCorrectionLevel.H);
            if (isUrl) { content = content.Replace('|', '&'); }
            QrCode qrCode = encoder.Encode(content);
            if (width <= 0) { width = 200; }
            var renderer = new GraphicsRenderer(new FixedCodeSize(width, QuietZoneModules.Two));
            if (height <= 0) { height = 200; }
            System.Drawing.Image imgCode = new Bitmap(width, height);
            using (Graphics g = Graphics.FromImage(imgCode))
            {
                renderer.Draw(g, qrCode.Matrix);
            }
            return imgCode;
        }
    }
}
